Home:ALL Converter>Inserting record to nested array using MongoDB and PHP

Inserting record to nested array using MongoDB and PHP

Ask Time:2013-06-18T18:24:36         Author:Ryan

Json Formatter

I have a collection in MongoDB called topic

topic{
    topic_title: 'thread',
    reply{
        reply_title: 'thread',
        reply_content: 'content'
        reply_created: "2013-06-18 17:54:04" 
    }

}

I wanted to add a reply to the topic like:

topic{
    topic_title: 'thread',
    reply{
        reply_title: 'thread',
        reply_content: 'content'
        reply_created: "2013-06-18 17:54:04" 
    }
    {
        reply_title: 'reply1',
        reply_content: 'reply2'
        reply_created: "2013-06-18 17:57:04" 
            }
}

my code goes like this:

   $reply = array(
                            "reply_title" => $title,
                            "reply_content" =>$content,
                            "reply_created" => date('Y-m-d H:i:s')
        );
    $document = array('$push' => array("reply" => $reply));

    $id = new MongoId($topicid);
    $topic->update(array("_id"=>$id),$document);

and it did something like this

     topic{
           topic_title: 'replytitle'
           reply {
                    reply_title: "replytitle"
                    reply_content: "replycontent"
                    reply_created: "2013-06-18 17:57:12"
                 }

          }
      reply{
            reply{
                    reply_title: "replytitle"
                    reply_content: "replycontent"
                    reply_created: "2013-06-18 17:57:12"
             }
            reply{
                    reply_title: "replytitle"
                    reply_content: "replycontent"
                    reply_created: "2013-06-18 17:57:12"
             }
           }

I am really having a hard time doing a simple thing. which is add a reply to the reply array. Any help out there?

Author:Ryan,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/17166506/inserting-record-to-nested-array-using-mongodb-and-php
yy